﻿using MaterialDesignColors.WpfExample.Domain;
using MaterialDesignThemes.Wpf;
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using WpfApp1.Report;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        SQLiteHelper sqlite = new SQLiteHelper();
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new TextFieldsViewModel();
            
            lang =sqlite.getValue("select * from sys_config where name='lang' ", "value");

            string rest_name = sqlite.getValue("select * from sys_config where name='resturant_name' and lang='" + lang + "' ", "value");

            if (!lang.Equals("ug"))
            {
                if (string.IsNullOrEmpty(rest_name))
                {
                    //ShowMessage("提示", 1, "系统没有初始化，请填写初始数据");
                    MessageBox.Show("系统没有初始化，请填写初始数据");
                    WindowInit windowInit = new WindowInit();
                    windowInit.Owner = this;
                    windowInit.lang = lang;
                    windowInit.Show();
                   // this.Close();
                    return;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(rest_name))
                {
                    //ShowMessage("ئەسكەرتىش", 1, "سىستېما دەسلەپكى ئۇچۇرلىرىنى تولدۇرۇڭ");
                    MessageBox.Show("سىستېما دەسلەپكى ئۇچۇرلىرىنى تولدۇرۇڭ");
                    WindowInit windowInit = new WindowInit();
                    windowInit.Owner = this;
                    windowInit.lang = lang;
                    windowInit.Show();
                    // this.Close();
                    return;
                }
            }

            


            string order_get_time = sqlite.getValue("select * from sys_config where name='order_interval'", "value");
            if (string.IsNullOrEmpty(order_get_time))
            {
                if (lang.Equals("ug"))
                {
                    //ShowMessage("ئەسكەرتىش", 1, "سىستېما دەسلەپكى ئۇچۇرلىرىنى تولدۇرۇڭ");

                    MessageBox.Show("سىستېما دەسلەپكى ئۇچۇرلىرىنى تولدۇرۇڭ");
                    WindowInit windowInit = new WindowInit();
                    windowInit.Owner = this;
                    windowInit.lang = lang;
                    windowInit.Show();
                    // this.Close();
                    return;
                }
                else
                {
                    //ShowMessage("提示", 1, "系统没有初始化，请填写初始数据");
                    MessageBox.Show("系统没有初始化，请填写出事数据");
                    WindowInit windowInit = new WindowInit();
                    windowInit.Owner = this;
                    windowInit.lang = lang;
                    windowInit.Show();
                    // this.Close();
                    return;

                }
               
            }
            double d = double.Parse(order_get_time);
            TimeSpan span = TimeSpan.FromSeconds(d);
            timer.Interval = span;
            timer.Tick += Timer_Tick;
            
            timer2.Interval = TimeSpan.FromSeconds(d);
            timer2.Tick += Timer2_Tick;
        }

        bool flag_start=false;
        // <summary>
        /// 获取启动参数
        /// </summary>
        /// <param name="args"></param>
        public void ShowEx(string[] args)
        {
            string a1 = args[0];
            if (!string.IsNullOrEmpty(a1))
            {
                if (a1.Equals("true"))
                {
                    flag_start = true;
                }
            }
        }

        private delegate void UpdateUIDelegate1();

        private void UpdateUIThreadTest1()
        {
            var th = new Thread(ThreadUpdateUI1);
            th.Start();
        }

        private void ThreadUpdateUI1()
        {
            UpdateUIDelegate1 updateUIDelegate = new UpdateUIDelegate1(UpdateUI1);
            this.Dispatcher.Invoke(updateUIDelegate);
        }

        private void UpdateUI1()
        {
            getOrders();
            setDetailStatus(1);
            loadGrid3();
            printOrder();
        }

        private void setDetailStatus(int type)
        {
            string sql = "update 'order_detail' set status='2' where status is null ";
            switch (type)
            {
                case 1:
                    
                    sqlite.update(sql);


                    break;
                case 2:
                    sql = "update 'order_out_detail' set status='2' where status is null "; 
                    sqlite.update(sql);
                    break;
            }
        }

        private delegate void UpdateUIDelegate2();

        private void UpdateUIThreadTest2()
        {
            var th = new Thread(ThreadUpdateUI2);
            th.Start();
        }

        private void ThreadUpdateUI2()
        {
            UpdateUIDelegate2 updateUIDelegate = new UpdateUIDelegate2(UpdateUI2);
            this.Dispatcher.Invoke(updateUIDelegate);
        }

        private void UpdateUI2()
        {
            getOrderOut();
            setDetailStatus(2);
            loadGrid3();
            printOrderOut();
        }

        private delegate void UpdateUIDelegate3();

        private void UpdateUIThreadTest3()
        {
            var th = new Thread(ThreadUpdateUI3);
            th.Start();
        }

        private void ThreadUpdateUI3()
        {
            UpdateUIDelegate3 updateUIDelegate = new UpdateUIDelegate3(UpdateUI3);
            this.Dispatcher.Invoke(updateUIDelegate);
        }
        
        private void UpdateUI3()
        {
            service.syncFood(lang);
            loadGrid1(null);
        }

        private void Timer2_Tick(object sender, EventArgs e)
        {
            UpdateUIThreadTest2();
        }

        // int order_ct = 0;
        private void Timer_Tick(object sender, EventArgs e)
        {
            UpdateUIThreadTest1();
        }

        private void getOrders()
        {
            DataTable dt = sqlite.getData("select id from 'order' where lang='" + lang + "' order by id desc limit 1");
            string max_id = "0";
            if (dt.Rows.Count > 0)
            {
                max_id = dt.Rows[0]["id"].ToString();
            }
            string order_count_str = service.getOrder(max_id, lang);

            if (!string.IsNullOrEmpty(order_count_str))
            {
                fail_count2++;
            }
            else
            {
                fail_count2 = 0;
            }

            if (fail_count2 > 5)
            {
                tip(order_count_str+"("+fail_count2+")");

            }

            if (fail_count2 > 10)
            {
                stopService();
            }
        }

        int fail_count1 = 0;
        int fail_count2 = 0;

        private void getOrderOut()
        {
            DataTable dt = sqlite.getData("select id from 'order_out' where lang='" + lang + "' order by id desc limit 1");
            string max_id = "0";
            if (dt.Rows.Count > 0)
            {
                max_id = dt.Rows[0]["id"].ToString();
            }

            string order_count_str = service.getOrderOut(max_id, lang);

            if (!string.IsNullOrEmpty(order_count_str))
            {
                fail_count1++;
            }
            else
            {
                fail_count1 = 0;
            }

            if (fail_count1 > 5)
            {
                tip(order_count_str + "(" + fail_count1 + ")");
                
            }

            if (fail_count1 > 10)
            {
                stopService();
            }
            
            // int ct = 0;
            // int.TryParse(order_count_str, out ct);
            //order_ct += ct;
        }


        private  void  tip(string msg)
        {
            // if (type == 1)
            // {
            //     MainSnackbar.MessageQueue.Enqueue(msg);
            // }else if (type == 2)
            // {
            //     MainSnackbar2.MessageQueue.Enqueue(msg);
            // }
            // else if (type == 3)
            // {
            //     MainSnackbar3.MessageQueue.Enqueue(msg);
            // }
            MainSnackbar.MessageQueue.Enqueue(msg);
            MainSnackbar2.MessageQueue.Enqueue(msg);
            MainSnackbar3.MessageQueue.Enqueue(msg);
        }

        public static string excuteCmd(string cmd)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardInput = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.Arguments = "/c " + cmd;
            proc.Start();
            proc.WaitForExit();
            string ret = "";// proc.StandardOutput.ReadToEnd() + proc.StandardError.ReadToEnd();
            //Console.WriteLine(ret);
            return ret;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string lg=sqlite.getValue("select value from sys_config where name='lang'", "value");
            if (!lg.Equals("ug"))
            {
                setlanguage(false);
            }
            else
            {
                setlanguage(true);
            }

            string primary_color = "Teal";
            string prc = sqlite.getValue("select value from sys_config where name='primary_color'", "value");
            if (!string.IsNullOrEmpty(prc))
            {
                primary_color = prc;
            }

            new PaletteHelper().ReplacePrimaryColor(primary_color);

            bool isDark = false;

            string isd = sqlite.getValue("select value from sys_config where name='is_dark'", "value");
            if (!string.IsNullOrEmpty(isd))
            {
                if (isd.Equals("1"))
                {
                    isDark = true;
                }
            }
            
            new PaletteHelper().SetLightDark(isDark);    

            getDefault();

            //临时
            //service.syncFood(lang);
            //loadGrid1(null);
            //getOrders();
            //loadGrid3();

            //临时
            if (flag_start)
            {
                startService();
            }
            //tip(1,"start up");
        }

        private void getDefault()
        {
            loadGrid1(null);
            
            loadGrid2();
            
            loadGrid3();

            try
            {
                excuteCmd(" net start Spooler ");
            }
            catch
            {

            }

        }

        private void loadGrid1(string name)
        {
            string where = "";
            if (name != null)
            {
                where += " and "+name;
            }
            DataTable dt=sqlite.getData("select * from food_view where lang='" + lang + "'" + where);
            dgv1.ItemsSource = dt.DefaultView;
        }

        private void loadGrid2()
        {
            DataTable table = sqlite.getData("select * from printer_view where lang='" + lang + "'");
            dgv2.ItemsSource = table.DefaultView;
        }

        private void loadGrid3()
        {
            if (dgv3.Visibility == Visibility.Visible)
            {

                DataTable table = sqlite.getData("select * from 'order_view' where lang='" + lang + "' ORDER BY id desc ");
                dgv3.ItemsSource = table.DefaultView;

            }
            if (dgv4.Visibility == Visibility.Visible)
            {
                DataTable table2 = sqlite.getData("select * from 'order_out_view' where lang='" + lang + "' ORDER BY id desc ");
                dgv4.ItemsSource = table2.DefaultView;
            }


        }

        string default_name = "";

        private void ToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            ToggleButton tbtn = (ToggleButton)sender;
            string name = tbtn.Name;
            switch (name)
            {
                case "toggle_lang":
                    setlanguage(tbtn.IsChecked.Value);
                    break;
                case "toggle_light":
                    new PaletteHelper().SetLightDark(tbtn.IsChecked.Value);
                    Palette p = new PaletteHelper().QueryPalette();
                    default_name = p.PrimarySwatch.Name;
                    break;
            }

            // MessageBox.Show(default_name);
        }

        public string lang = "";

        private void setlanguage(bool isUg)
        {
            if (isUg)
            {
                lang = "ug";
                this.FlowDirection = FlowDirection.RightToLeft;

                //  btn_changetab0.Content = "مۇلازىمەت";
                // btn_changetab1.Content = "تائاملار";
                txt_food_label.Text= "تائاملار";
                // btn_changetab2.Content = "ئۈسكۈنە باشقۇرۇش";
                txt_device_label.Text= "پىرىنتېر ";
                txt_order_label.Text = "زاكاس تىزىملىكى";
                // btn_changetab3.Content = "زاكاس تىزىملىكى";
                s_start_txt.Text = "زاكاز نى باشلاش";
                s_stop_txt.Text = "زاكازنى توختىتىش";
                s_food_txt.Text = "تائاملار";
                s_device_txt.Text = "پىرىنتېر ";
                s_order_txt.Text = "زاكاز خاتىرىسى";
                s_finance_txt.Text = "ھېسابات";
                s_setting_txt.Text = "تەڭشەك";
                txt_finance_label.Text = "ھېسابات";

                btn_today.Content = "بۈگۈن";
                btn_week.Content = "بۇ ھەپتە";
                    btn_month.Content = "مۇشۇ ئاي";
                btn_money_search.Content = "ئىزدەش";

                HintAssist.SetHint(menu1, "تەڭشەك");
                menu1_item1.Content = "سىستىمىنى قايتىدىن دەسلەپلەشتۈرۈش";

             //   tabitem0.Header = "مۇلازىمەت";
             //   btn_start_service.Content = "زاكاس ئېلىشنى باشلاش";
             //   btn_stop_service.Content = "زاكاس ئېلىشنى توختىتىش";


             //   tabitem1.Header = "تائاملار";
             //   tabitem2.Header = "ئۈسكۈنە باشقۇرۇش";
             //   tabitem3.Header = "زاكاس تىزىملىكى";
             //  tabitem4.Header = "سىستېما تەڭشىكى";
             //
             //  lb_lang.Text = "تىل تەڭشىكى";
             //  lb_theme.Text = "ئۇسلۇب تەڭشىكى";
             //  lb_light.Text = "يورۇق";
             //  lb_dark.Text = "قاراڭغۇ";
             //  HintAssist.SetHint(primarycolor_combo, "ئاساسىي رەڭ");
             //  HintAssist.SetHint(secondarycolor_combo, "قوشۇمچە رەڭ");
             //  lb_params.Text = "پارامېتېر تەڭشىكى";
             //
             //  HintAssist.SetHint(txt_resturant_name_ug, "ئاشخانا ئىسمى");
             //  HintAssist.SetHint(txt_resturant_name_zh, "ئاشخانا ئىسمى (خەنزۇچە)");
             //  HintAssist.SetHint(txt_resturant_tag, "چۈشەندۈرۈش");
             //  HintAssist.SetHint(txt_resturant_tel, "تېلىفون");
             //  HintAssist.SetHint(txt_resturant_address_ug, "ئادرىسى");
             //
             //  HintAssist.SetHint(txt_resturant_opentime, "ئېچىلغان ۋاقتى");
             //  HintAssist.SetHint(txt_resturant_closetime, "توختىتىلىدىغان ۋاقتى");
             //  HintAssist.SetHint(txt_resturant_id, "ئاشخاناID");
             //  HintAssist.SetHint(txt_resturant_secret, "ئاشخانا پارولى");
             //
             //  HintAssist.SetHint(txt_status, "ھالىتى");
             //  HintAssist.SetHint(txt_order_interval, "توردىن زاكاس يېڭىلاش ۋاقىت ئارىلىقى)سېكۇنت)");
             //
             //  params_btn_save.Content = "ساقلاش";
             //  params_btn_clear.Content = "تازىلاش";

                btn_snc.Content = "توردىن ئۇچۇر يېڭىلاش";
                btn_refresh.Content = "يېڭىلاش";
                HintAssist.SetHint(food_txt_search, "ئىزدەش");
                food_btn_search.Content = "ئىزدەش";
                food_btn_food_type.Content = "تاماق تۈرى";
                food_btn_food_edit.Content = "تەھرىرلەش";

                food_col_id.Header = "نومۇرى";
                
                food_col_food_name.Header = "ئىسمى";
                food_col_price.Header = "باھاسى";
                food_col_image.Header = "رەسىم";
                food_col_description.Header = "چۈشەندۈرۈش";
                food_col_food_type.Header = "تاماق تۈرى";

                food_col_food_state.Header = "ھالىتى";

                money_col_food_name.Header = "تاماق ئىسمى";
                money_col_paid_price.Header = "تۆلەنگەن سومما";
                money_col_paid_count.Header = "تۆلەنگەن سانى";
                money_col_canceled_price.Header = "ئەمەلدىن قالدۇرۇلغان سومما";
                money_col_canceled_count.Header = "ئەمەلدىن قالدۇرۇلغان سانى";

                dgv1_col_operation.Header = "مەشغۇلات";

                device_add.Content = "قوشۇش";
                device_reload.Content = "يېڭىلاش";

                device_bind.Content = "باغلاش";
                device_edit.Content = "تەھرىرلەش";
                device_del.Content = "ئۆچۈرۈش";



                dgv2_col_printer_alias.Header = "ئىسمى";
                dgv2_col_printer_name.Header = " ئۈسكۈنە ئىسمى";
                dgv2_col_printer_type.Header = "پىرىنتېر تۈرى";
                dgv2_col_stutus.Header = "ھالىتى";

                order_btn_add.Content = "قوشۇش";
                order_btn_reload.Content = "يېڭىلاش";
                order_btn_view.Content = "كۆرۈش";
                order_btn_del.Content = "ئۆچۈرۈش";
                order_btn_detail.Content = "تەپسىلاتى";
                order_btn_print.Content = "بېسىش";


                btn_order_type1.Content = "ئۈندىداردا چۈشۈرۈلگەن زاكاز";

                btn_order_type2.Content = "سىرتقا توشۇلىدىغان زاكاز";
              //  lb_order.Text = "قوبۇل قىلغان زاكاز سانى";


                dgv3_col_id.Header = "نومۇرى";
                dgv3_col_ordernumber.Header = "نومۇرى";
                dgv3_col_table_name.Header = "ئۈستەل ئىسمى";
                dgv3_col_ordertime.Header = "ۋاقتى";
                dgv3_col_price.Header = "زاكاس سوممىسى";
                dgv3_col_state.Header = "ھالىتى";

                dgv3_col_operation.Header = "مەشغۇلات";


                dgv4_col_id.Header = "نومۇرى";
                dgv4_col_ordernumber.Header = "نومۇرى";
                dgv4_col_table_name.Header = "تاپشۇرۇۋالغۇچى";
                dgv4_col_ordertime.Header = "ۋاقتى";
                dgv4_col_price.Header = "زاكاس سوممىسى";
                dgv4_col_state.Header = "ھالىتى";

                dgv4_col_operation.Header = "مەشغۇلات";
            }
            else
            {
                lang = "cn";
                this.FlowDirection = FlowDirection.LeftToRight;
                s_start_txt.Text = "启动服务";
                s_stop_txt.Text = "停止服务";
                s_food_txt.Text = "美食";
                s_food_txt.Text = "设备管理";
                s_order_txt.Text = "订单记录";
                s_finance_txt.Text = "账单";
                s_setting_txt.Text = "参数设置";
                txt_device_label.Text = "设备管理";
                txt_order_label.Text= "订单记录";
                //  btn_changetab0.Content = "服务";
                //  btn_changetab1.Content = "美食";
                //  btn_changetab2.Content = "设备管理";
                //  btn_changetab3.Content = "订单记录";

                HintAssist.SetHint(menu1, "设置");
                menu1_item1.Content = "初始化设置";

              //  tabitem0.Header = "服务";
                
              //  btn_start_service.Content = "开始接订单";
             //   btn_stop_service.Content = "停止接订单";

              //  tabitem1.Header = "美食";
                
              //  tabitem2.Header = "设备管理";
                
              //  tabitem3.Header = "订单记录";
                
                //   tabitem4.Header = "系统设置";
                //
                //   lb_lang.Text = "语言设置";
                //   lb_theme.Text = "主题设置";
                //   lb_light.Text = "光亮";
                //   lb_dark.Text = "暗黑";
                //   HintAssist.SetHint(primarycolor_combo, "主要颜色");
                //   HintAssist.SetHint(secondarycolor_combo, "次要颜色");
                //   lb_params.Text = "参数设置";
                //
                //   HintAssist.SetHint(txt_resturant_name_ug, "饭店名称(维吾尔语)");
                //   HintAssist.SetHint(txt_resturant_name_zh, "饭店名称(汉语)");
                //   HintAssist.SetHint(txt_resturant_tag, "注释");
                //   HintAssist.SetHint(txt_resturant_tel, "电话");
                //   HintAssist.SetHint(txt_resturant_address_ug, "地址(维吾尔语)");
                //
                //   HintAssist.SetHint(txt_resturant_opentime, "开业时间");
                //   HintAssist.SetHint(txt_resturant_closetime, "停业时间");
                //   HintAssist.SetHint(txt_resturant_id, "饭店ID");
                //   HintAssist.SetHint(txt_resturant_secret, "饭店密码");
                //
                //   HintAssist.SetHint(txt_status, "状态");
                //   HintAssist.SetHint(txt_order_interval, "订单读取间隔(秒)");
                //
                //   params_btn_save.Content = "保存";
                //   params_btn_clear.Content = "清空";

                btn_snc.Content = "同步";
                btn_refresh.Content = "刷新";
                HintAssist.SetHint(food_txt_search, "查找");
                food_btn_search.Content = "查找";
                food_btn_food_type.Content = "饭菜类型";
                food_btn_food_edit.Content = "编辑";

                food_col_id.Header = "编号";
                
                food_col_food_name.Header = "名称";
                food_col_price.Header = "价格";
                food_col_image.Header = "图片";
                food_col_description.Header = "介绍";
                food_col_food_type.Header = "饭菜类型";
                food_col_food_state.Header = "状态";

                dgv1_col_operation.Header = "操作";

                device_add.Content = "添加";
                device_reload.Content = "刷新";
                device_bind.Content = "绑定";
                device_edit.Content = "编辑";
                device_del.Content = "删除";

                dgv2_col_printer_alias.Header = "名称";
                dgv2_col_printer_name.Header = "设备名称";
                dgv2_col_stutus.Header = "状态";

                order_btn_add.Content = "添加";
                order_btn_reload.Content = "刷新";
                order_btn_view.Content = "查看";
                order_btn_del.Content = "删除";
                order_btn_detail.Content = "详细";
                order_btn_print.Content = "打印";

                btn_order_type1.Content = "扫码点餐订单";

                btn_order_type2.Content = "外卖订单";


                // lb_order.Text = "接收到的订单数量";


                dgv3_col_id.Header = "编号";
                dgv3_col_ordernumber.Header = "编号";
                dgv3_col_table_name.Header = "桌子名称";
                dgv3_col_ordertime.Header = "时间";
                dgv3_col_price.Header = "订单金额";
                dgv3_col_state.Header = "状态";
                dgv3_col_operation.Header = "操作";


                dgv4_col_id.Header = "编号";
                dgv4_col_ordernumber.Header = "编号";
                dgv4_col_table_name.Header = "收货人";
                dgv4_col_ordertime.Header = "时间";
                dgv4_col_price.Header = "订单金额";
                dgv4_col_state.Header = "状态";
                dgv4_col_operation.Header = "操作";
            }
        }

        DispatcherTimer timer = new DispatcherTimer();

        DispatcherTimer timer2 = new DispatcherTimer();

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            string name = btn.Name;
            switch (name)
            {
                case "btn_changetab0":
                    startService();
                    break;
                case "btn_changetab0_1":
                    stopService();
                    break;
                case "btn_changetab1":
                    grid_food.Visibility = Visibility.Visible;
                    grid_device.Visibility = Visibility.Hidden;
                    grid_order.Visibility = Visibility.Hidden;
                    grid_money.Visibility = Visibility.Hidden;

                    // tab1.SelectedIndex = 1;
                    break;
                case "btn_changetab2":
                    grid_food.Visibility = Visibility.Hidden;
                    grid_device.Visibility = Visibility.Visible;
                    grid_order.Visibility = Visibility.Hidden;
                    grid_money.Visibility = Visibility.Hidden;
                    // tab1.SelectedIndex = 2;
                    break;
                case "btn_changetab02":
                    grid_food.Visibility = Visibility.Hidden;
                    grid_device.Visibility = Visibility.Hidden;
                    grid_order.Visibility = Visibility.Hidden;
                    grid_money.Visibility = Visibility.Visible;

                    break;
                case "btn_changetab3":
                    grid_food.Visibility = Visibility.Hidden;
                    grid_device.Visibility = Visibility.Hidden;
                    grid_order.Visibility = Visibility.Visible;
                    grid_money.Visibility = Visibility.Hidden;

                    //  tab1.SelectedIndex = 3;
                    break;
                case "btn_changetab4":
                    string msg = "";
                    string title1 = "";

                    if (lang.Equals("ug"))
                    {
                        msg = "سىستېمىنى راستىنلا قايتىدىن دەسلەپلەشتۈرەمسىز؟";
                        title1 = "ئەسكەرتىش";
                    }
                    else
                    {
                        msg = "确定要重新初始化系统吗?";
                        title1 = "提示";
                    }

                    if (MessageBox.Show(msg, title1, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        stopService();
                        WindowInit windowInit = new WindowInit();
                        windowInit.Owner = this;
                        windowInit.lang = lang;
                        windowInit.Show();
                        // this.Close();
                    }

                    break;
                case "btn_food_move_down":
                   // scroll_food.ScrollToVerticalOffset(scroll_food.VerticalOffset - 50);
                    
                    break;
                case "btn_food_move_up":
                   // scroll_food.ScrollToVerticalOffset(scroll_food.VerticalOffset + 50);

                    break;
                case "food_btn_detail1":
                    FoodEdit foodEdit = new FoodEdit();
                    if (dgv1.SelectedItem != null)
                    {
                        DataRowView row = (DataRowView)dgv1.SelectedItem;
                        string id = row.Row.ItemArray[0].ToString();
                        foodEdit.id = id;
                        foodEdit.lang = lang;
                        foodEdit.Owner = this;
                        foodEdit.ShowDialog();
                        loadGrid1(null);
                    }


                        break;
                case "device_add":
                    DeviceAddWindow deviceAddWindow = new DeviceAddWindow();
                    deviceAddWindow.lang = lang;
                    deviceAddWindow.Owner = this;
                    deviceAddWindow.ShowDialog();
                    loadGrid2();
                    break;
                case "device_reload":
                    loadGrid2();
                    break;
                case "order_btn_reload":
                    loadGrid3();
                    break;
                case "order_btn_add":

                    break;
                case "order_btn_view":

                    break;
                case "order_btn_del":

                    break;
                case "order_btn_print1":
                   
                    printOne();

                    break;
                case "order_btn_print2":

                    printTwo();

                    break;
                case "order_btn_detail1":

                    if (dgv3.SelectedItem != null)
                    {
                        DataRowView row = (DataRowView)dgv3.SelectedItem;
                        string id = row.Row.ItemArray[0].ToString();
                        OrderDetailWindow orderDetailWindow = new OrderDetailWindow();
                        orderDetailWindow.Owner = this;
                        orderDetailWindow.id = id;
                        orderDetailWindow.lang = lang;
                        orderDetailWindow.ShowDialog();
                        loadGrid3();
                    }

                    break;
                case "order_btn_detail2":

                    if (dgv4.SelectedItem != null)
                    {
                        DataRowView row = (DataRowView)dgv4.SelectedItem;
                        string id = row.Row.ItemArray[0].ToString();
                        OrderDetailWindow orderDetailWindow = new OrderDetailWindow();
                        orderDetailWindow.Owner = this;
                        orderDetailWindow.id = id;
                        orderDetailWindow.tt = 1;
                        orderDetailWindow.lang = lang;
                        orderDetailWindow.ShowDialog();
                        loadGrid3();
                    }

                    break;
                case "device_bind":

                    DeviceBindWindow deviceBindWindow = new DeviceBindWindow();
                         
                    deviceBindWindow.lang = lang;
                    deviceBindWindow.Owner = this;
                    deviceBindWindow.ShowDialog();

                    break;
                case "device_edit":
                    if (dgv2.SelectedItem != null)
                    {
                        DataRowView row = (DataRowView)dgv2.SelectedItem;
                        string id = row.Row.ItemArray[0].ToString();
                        deviceAddWindow = new DeviceAddWindow();
                        deviceAddWindow.id = id;
                        deviceAddWindow.lang = lang;
                        deviceAddWindow.Owner = this;
                        deviceAddWindow.ShowDialog();
                        loadGrid2();
                    }

                    break;
                case "device_del":
                    if (dgv2.SelectedItem != null)
                    {
                        DataRowView row = (DataRowView)dgv2.SelectedItem;
                        string id = row.Row.ItemArray[0].ToString();
                        msg = "";
                        title1 = "";

                        if (lang.Equals("ug"))
                        {
                            msg = "راستىنلا ئۆچۈرەمسىز؟";
                            title1 = "ئەسكەرتىش";
                        }
                        else
                        {
                            msg = "确定要删除吗?";
                            title1 = "提示";
                        }

                        if (MessageBox.Show(msg, title1, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                        {
                            sqlite.execute("delete from printer where id=" + id);
                            sqlite.execute("delete from printer_binding where printer_id=" + id);
                            loadGrid2();
                        }
                    }

                    break;
                case "btn_start_service":
                      
                    break;
                case "btn_stop_service":
                    
                    break;
            }
        }

        private void startService()
        {
            string printer_alias1 = sqlite.getValue("select name from printer where print_type='1' and status='1' and lang='" + lang + "'", "name");
            string printer_alias2 = sqlite.getValue("select name from printer where print_type='2' and status='1' and lang='" + lang + "'", "name");
            string printer_alias3 = sqlite.getValue("select name from printer where print_type='3' and status='1' and lang='" + lang + "'", "name");
            string printer_alias4 = sqlite.getValue("select name from printer where print_type='4' and status='1' and lang='" + lang + "'", "name");

            string msg = "没有添加打印机或打印机未启用";
            
            if (string.IsNullOrEmpty(printer_alias1))
            {
                if (lang.Equals("ug"))
                {
                    msg = "پىرىنتېر قوشۇلمىغان ياكى ھالىتى ئوچۇق ئەمەس";
                    msg = "باش تالون " + msg;
                }
                else
                {
                    msg = " 总单 " + msg;
                }
               // tip(msg);
               // return;
            }
            else if (string.IsNullOrEmpty(printer_alias2))
            {
                if (lang.Equals("ug"))
                {
                    msg = "پىرىنتېر قوشۇلمىغان ياكى ھالىتى ئوچۇق ئەمەس";
                    msg = "   ئاشخانا تاماق تالونى  " + msg;
                }
                else
                {
                    msg = " 分单 " + msg;
                }
               // tip(msg);
               // return;
            }
            else if (string.IsNullOrEmpty(printer_alias3))
            {
                if (lang.Equals("ug"))
                {
                    msg = "پىرىنتېر قوشۇلمىغان ياكى ھالىتى ئوچۇق ئەمەس";
                    msg = "  باش تالون سىرتقا توشۇلىدىغان " + msg;
                }
                else
                {
                    msg = " 外卖总单 " + msg;
                }
               // tip(msg);
            }
            else if (string.IsNullOrEmpty(printer_alias4))
            {
                if (lang.Equals("ug"))
                {
                    msg = "پىرىنتېر قوشۇلمىغان ياكى ھالىتى ئوچۇق ئەمەس";
                    msg = "  سىرتقا توشۇلىدىغان تاماق  " + msg;
                }
                else
                {
                    msg = " 外卖分单 " + msg;
                }
               // tip(msg);
            }

            int stat = Printer.GetPrinterStatusInt(printer_alias1);

            if (stat != 0)
            {
                msg=Printer.GetPrinterStatus(printer_alias1);
                // tip(msg);
                //  return;
            }

            stat = Printer.GetPrinterStatusInt(printer_alias2);

            if (stat != 0)
            {
                msg = Printer.GetPrinterStatus(printer_alias2);
               // tip(msg);
               // return;
            }

            stat = Printer.GetPrinterStatusInt(printer_alias3);

            if (stat != 0)
            {
                msg = Printer.GetPrinterStatus(printer_alias3);
               // tip(msg);
            }

            stat = Printer.GetPrinterStatusInt(printer_alias4);

            if (stat != 0)
            {
                msg = Printer.GetPrinterStatus(printer_alias4);
               // tip(msg);
            }

            btn_changetab0.IsEnabled = false;
            btn_changetab0_1.IsEnabled = true;

            timer.IsEnabled = true;

            timer2.IsEnabled = true;
        }

        private void stopService()
        {
            btn_changetab0.IsEnabled = true;
            btn_changetab0_1.IsEnabled = false;
            timer.IsEnabled = false;
            timer2.IsEnabled = false;
        }

        private void printOne()
        {
            if (dgv3.SelectedItem != null)
            {
                //string printerName = sqlite.getValue("select device_name from printer where print_type='1' and status='1' and lang='" + lang + "' ", "device_name");

                DataRowView row = (DataRowView)dgv3.SelectedItem;
                string id = row.Row.ItemArray[0].ToString();//.ItemArray[0].ToString();

                string sql = "select * from printer where print_type='1' and status='1' and lang='" + lang + "' ";

                sql = "select * from printer where print_type='1'  and lang='" + lang + "' ";

                DataRow drow=sqlite.getDataRow(sql);
                if (drow != null)
                {
                   // return;
                 
                string printerName = drow["device_name"].ToString();
                string paper_width_txt = drow["paper_width"].ToString();
                string paper_height_txt = drow["paper_height"].ToString();
                string printCount = drow["print_count"].ToString();

                DataRow order_row = sqlite.getDataRow("select * from 'order' where id='"+id+"' and lang='"+lang+"'");

                List<Orders2> orders = new List<Orders2>();

                    if (order_row != null)
                    {
                        string report_wenjianming = "Report1.rdlc";

                        string order_number = order_row["order_number"].ToString();
                        string table_name = order_row["table_name"].ToString();
                        string created_at = order_row["created_at"].ToString();
                        string price = order_row["price"].ToString();
                        string description = order_row["description"].ToString();

                        DataTable order_detail = sqlite.getData("select * from 'order_detail_view' where order_id='" + id + "' and lang='" + lang + "' ");

                        for (int j = 0; j < order_detail.Rows.Count; j++)
                        {
                            string food_name_ug = order_detail.Rows[j]["food_name"].ToString();
                            string food_price = order_detail.Rows[j]["price"].ToString();
                            string food_number = order_detail.Rows[j]["number"].ToString();
                            string tablename = order_detail.Rows[j]["table_name"].ToString();

                            int ct = 0;
                            int.TryParse(food_number, out ct);

                            Orders2 orders1 = new Orders2(food_name_ug, food_price, ct, tablename);

                            orders.Add(orders1);
                        }

                        List<ReportParameter> pr1 = new List<ReportParameter>();

                        string resturant_name = sqlite.getValue("select value from sys_config where name='resturant_name' and lang='" + lang + "' ", "value");

                        //description=

                        pr1.Add(new ReportParameter("resturant_name", resturant_name, true));

                        pr1.Add(new ReportParameter("table_name", table_name, true));
                        pr1.Add(new ReportParameter("order_number", order_number, true));
                        pr1.Add(new ReportParameter("time", created_at, true));
                        pr1.Add(new ReportParameter("price", price, true));
                        pr1.Add(new ReportParameter("description", description, true));


                        string path = Environment.CurrentDirectory;

                        LocalReport localReport = new LocalReport();
                        localReport.ReportPath = path + @"\Report\" + report_wenjianming;

                       // string printCount = sqlite.getValue("select print_count from printer where print_type='1' and status='1' and lang='" + lang + "' ", "print_count");

                        //  for (int index = 0; index < cct; index++)
                        //  {
                        RDLCPrint aa = new RDLCPrint(false,false);
                        int width = 0;
                        int.TryParse(paper_width_txt, out width);
                        if (width <= 0)
                        {
                            return;
                        }

                        int height = 0;
                        int.TryParse(paper_height_txt, out height);
                        if (height <= 0)
                        {
                            return;
                        }


                        if (!string.IsNullOrEmpty(printerName))
                        {
                            aa.Run(localReport, "DataSet1", orders, pr1, printerName, id, printCount, width, height);
                            //   }
                        }
                    }

                   
                }

                PrintDetails(id, true);

                string ct1 = sqlite.getValue("select count(*) as ct from order_detail where order_id='" + id + "' and status='2'", "ct");
                if (ct1.Equals("0"))
                {
                    sqlite.execute("update 'order' set status='3' where id='" + id + "'");
                }

                loadGrid3();
            }
        }


        private void printTwo()
        {
            if (dgv4.SelectedItem != null)
            {
                // string printerName = sqlite.getValue("select device_name from printer where print_type='3' and status='1' and lang='" + lang + "' ", "device_name");


                DataRowView row = (DataRowView)dgv4.SelectedItem;
                string id = row.Row.ItemArray[0].ToString();//.ItemArray[0].ToString();


                DataRow drow = sqlite.getDataRow("select * from printer where print_type='3' and status='1' and lang='" + lang + "' ");
                if (drow != null)
                {
                    // return;

                    string printerName = drow["device_name"].ToString();
                    string paper_width_txt = drow["paper_width"].ToString();
                    string paper_height_txt = drow["paper_height"].ToString();

                    if (string.IsNullOrEmpty(printerName))
                    {
                        tip("پىرىنېتر تېپىلمىدى ياكى قوشۇلمىغان");
                        //MessageBox.Show("no printer found!");
                        return;
                    }


                    DataRow order_row = sqlite.getDataRow("select * from 'order_out' where id='" + id + "' and lang='" + lang + "'");

                    List<Orders2> orders = new List<Orders2>();

                    if (order_row != null)
                    {
                        string report_wenjianming = "Report3.rdlc";

                        string order_number = order_row["order_number"].ToString();
                        //  string table_name = order_row["table_name"].ToString();
                        string delivery_time = order_row["delivery_time"].ToString();
                        string price = order_row["price"].ToString();
                        string description = order_row["description"].ToString();

                        string pay_type = order_row["pay_type"].ToString(); ;
                        string delivery_fee = order_row["delivery_fee"].ToString(); ;
                        string receiver = order_row["receiver"].ToString(); ;
                        string address = order_row["address"].ToString(); ;
                        string phone = order_row["phone"].ToString(); ;

                        // if (lang.Equals("ug"))
                        // {
                        //     description = " ئەسكەرتىش" + description;
                        // }
                        // else
                        // {
                        //     description = "提示:" + description;
                        // }
                        DataTable order_detail = sqlite.getData("select * from 'order_out_detail_view' where order_id='" + id + "' and lang='" + lang + "' ");

                        for (int j = 0; j < order_detail.Rows.Count; j++)
                        {
                            string food_name_ug = order_detail.Rows[j]["food_name"].ToString();
                            string food_price = order_detail.Rows[j]["price"].ToString();
                            string food_number = order_detail.Rows[j]["number"].ToString();
                            string tablename = "";// order_detail.Rows[j]["table_name"].ToString();

                            int ct = 0;
                            int.TryParse(food_number, out ct);

                            Orders2 orders1 = new Orders2(food_name_ug, food_price, ct, tablename);

                            orders.Add(orders1);
                        }

                        List<ReportParameter> pr1 = new List<ReportParameter>();

                        string platform_name = sqlite.getValue("select value from sys_config where name='platform_name' and lang='" + lang + "' ", "value");

                        pr1.Add(new ReportParameter("platform_name", platform_name, true));
                        pr1.Add(new ReportParameter("order_number", order_number, true));
                        pr1.Add(new ReportParameter("time", delivery_time, true));
                        pr1.Add(new ReportParameter("price", price, true));
                        pr1.Add(new ReportParameter("description", description, true));
                        pr1.Add(new ReportParameter("pay_type", pay_type, true));
                        pr1.Add(new ReportParameter("delivery_fee", delivery_fee, true));
                        pr1.Add(new ReportParameter("receiver", receiver, true));
                        pr1.Add(new ReportParameter("address", address, true));
                        pr1.Add(new ReportParameter("phone", phone, true));

                        string path = Environment.CurrentDirectory;

                        LocalReport localReport = new LocalReport();
                        localReport.ReportPath = path + @"\Report\" + report_wenjianming;

                        string printCount = sqlite.getValue("select print_count from printer where print_type='3' and status='1' and lang='" + lang + "' ", "print_count");

                        //  for (int index = 0; index < cct; index++)
                        //  {
                        RDLCPrint aa = new RDLCPrint(false,false);

                        int width = 0;
                        int.TryParse(paper_width_txt, out width);
                        if (width <= 0)
                        {
                            return;
                        }

                        int height = 0;
                        int.TryParse(paper_height_txt, out height);
                        if (height <= 0)
                        {
                            return;
                        }

                        aa.Run2(localReport, "DataSet1", orders, pr1, printerName, id, printCount, width, height);
                        //   }


                    }
                }

                PrintDetails2(id, true);

                string ct1 = sqlite.getValue("select count(*) as ct from order_out_detail where order_id='" + id + "' and status='2'", "ct");
                if (ct1.Equals("0"))
                {
                    sqlite.execute("update 'order_out' set status='3' where id='" + id + "'");
                }


                loadGrid3();
            }
        }

        private void printOrder()
        {
            DataTable order_dt = sqlite.getData("select * from 'order' where status='2'");
            for (int i = 0; i < order_dt.Rows.Count; i++)
            {
                List<Orders> orders = new List<Orders>();

                string report_wenjianming = "Report1.rdlc";
                string id = order_dt.Rows[i]["id"].ToString();
                string order_number = order_dt.Rows[i]["order_number"].ToString();
                string table_name = order_dt.Rows[i]["table_name"].ToString();
                string created_at = order_dt.Rows[i]["created_at"].ToString();
                string price = order_dt.Rows[i]["price"].ToString();
                string description = order_dt.Rows[i]["description"].ToString();
              // if (lang.Equals("ug"))
              // {
              //     description = " ئەسكەرتىش " + description;
              // }
              // else
              // {
              //     description = "提示:" + description;
              // }

                DataTable order_detail = sqlite.getData("select * from 'order_detail_view' where order_id='" + id + "' and lang='"+lang+"' ");

                for (int j = 0; j < order_detail.Rows.Count; j++)
                {
                    string food_name_ug = order_detail.Rows[j]["food_name"].ToString();
                    string food_price = order_detail.Rows[j]["price"].ToString();
                    string food_number = order_detail.Rows[j]["number"].ToString();

                    int ct = 0;
                    int.TryParse(food_number, out ct);

                    Orders orders1 = new Orders(food_name_ug, food_price, ct, table_name);

                    orders.Add(orders1);
                }

                List<ReportParameter> pr1 = new List<ReportParameter>();
                string resturant_name = sqlite.getValue("select value from sys_config where name='resturant_name' and lang='" + lang+"'", "value");
                 
                pr1.Add(new ReportParameter("resturant_name", resturant_name, true));
                pr1.Add(new ReportParameter("table_name", table_name, true));
                pr1.Add(new ReportParameter("order_number", order_number, true));
                pr1.Add(new ReportParameter("time", created_at, true));
                pr1.Add(new ReportParameter("price", price, true));
                pr1.Add(new ReportParameter("description", description, true));
                
               

                string path = Environment.CurrentDirectory;

                LocalReport localReport = new LocalReport();
                localReport.ReportPath = path + @"\Report\" + report_wenjianming;

                //  string printCount = sqlite.getValue("select print_count from printer where print_type='1' and status='1' and lang='" + lang + "' ", "print_count");

                DataRow drow = sqlite.getDataRow("select * from printer where print_type='1' and status='1' and automatic='1' and lang='" + lang + "' ");
                if (drow != null)
                {
                    string printerName = drow["device_name"].ToString();
                    
                    string printCount = drow["print_count"].ToString();
                    
                    string paper_width_txt = drow["paper_width"].ToString();

                    string paper_height_txt = drow["paper_height"].ToString();


                    int width = 0;
                    int.TryParse(paper_width_txt, out width);
                    if (width <= 0)
                    {
                        return;
                    }

                    int height = 0;
                    int.TryParse(paper_height_txt, out height);
                    if (height <= 0)
                    {
                        return;
                    }


                    RDLCPrint aa = new RDLCPrint(false,false);
                    aa.isDetail1 = false;
                    aa.Run(localReport, "DataSet1", orders, pr1, printerName, id, printCount, width, height);



                }



                PrintDetails(id,false);

                string ct1=sqlite.getValue("select count(*) as ct from order_detail where order_id='"+id+"' and status='2'", "ct");
                if (ct1.Equals("0"))
                {
                    sqlite.execute("update 'order' set status='3' where id='" + id + "'");
                }
                

            }
            

        }

        private void printOrderOut()
        {
            DataTable order_dt = sqlite.getData("select * from 'order_out' where status='2' and lang='" + lang + "'");
            for (int i = 0; i < order_dt.Rows.Count; i++)
            {
                List<Orders> orders = new List<Orders>();

                string report_wenjianming = "Report3.rdlc";

                string id = order_dt.Rows[i]["id"].ToString();
                string order_number = order_dt.Rows[i]["order_number"].ToString();
                string delivery_time = order_dt.Rows[i]["delivery_time"].ToString();
                string price = order_dt.Rows[i]["price"].ToString();
                string description = order_dt.Rows[i]["description"].ToString();
                string pay_type = order_dt.Rows[i]["pay_type"].ToString(); ;
                string delivery_fee = order_dt.Rows[i]["delivery_fee"].ToString(); ;
                string receiver = order_dt.Rows[i]["receiver"].ToString(); ;
                string address = order_dt.Rows[i]["address"].ToString(); ;
                string phone = order_dt.Rows[i]["phone"].ToString(); ;

              //  if (lang.Equals("ug"))
              //  {
              //      description = " ئەسكەرتىش " + description;
              //  }
              //  else
              //  {
              //      description = "提示:" + description;
              //  }

                DataTable order_detail = sqlite.getData("select * from 'order_out_detail_view' where order_id='" + id + "' and lang='" + lang + "' ");

                for (int j = 0; j < order_detail.Rows.Count; j++)
                {
                    string food_name_ug = order_detail.Rows[j]["food_name"].ToString();
                    string food_price = order_detail.Rows[j]["price"].ToString();
                    string food_number = order_detail.Rows[j]["number"].ToString();
                    
                    int ct = 0;

                    int.TryParse(food_number, out ct);

                    Orders orders1 = new Orders(food_name_ug, food_price, ct, "");
                    
                    orders.Add(orders1);
                }

                List<ReportParameter> pr1 = new List<ReportParameter>();
                string platform_name = sqlite.getValue("select value from sys_config where name='platform_name' and lang='" + lang + "'", "value");

                pr1.Add(new ReportParameter("platform_name", platform_name, true));
                pr1.Add(new ReportParameter("order_number", order_number, true));
                pr1.Add(new ReportParameter("time", delivery_time, true));
                pr1.Add(new ReportParameter("price", price, true));
                pr1.Add(new ReportParameter("description", description, true));
                pr1.Add(new ReportParameter("pay_type", pay_type, true));
                pr1.Add(new ReportParameter("delivery_fee", delivery_fee, true));
                pr1.Add(new ReportParameter("receiver", receiver, true));
                pr1.Add(new ReportParameter("address", address, true));
                pr1.Add(new ReportParameter("phone", phone, true));

               

                string path = Environment.CurrentDirectory;

                LocalReport localReport = new LocalReport();

                localReport.ReportPath = path + @"\Report\" + report_wenjianming;

                

                DataRow drow = sqlite.getDataRow("select * from printer where print_type='3' and status='1' and automatic='1' and lang='" + lang + "' ");
                if (drow != null)
                {

                    string printCount = drow["print_count"].ToString();
                    string printerName = drow["device_name"].ToString();
                    string paper_width_txt = drow["paper_width"].ToString();
                    string paper_height_txt = drow["paper_height"].ToString();

                    int width = 0;
                    int.TryParse(paper_width_txt, out width);
                    if (width <= 0)
                    {
                        return;
                    }

                    int height = 0;
                    int.TryParse(paper_height_txt, out height);
                    if (height <= 0)
                    {
                        return;
                    }


                    RDLCPrint aa = new RDLCPrint(false, false);
                    aa.isDetail2 = false;

                    aa.Run2(localReport, "DataSet1", orders, pr1, printerName, id, printCount, width, height);

                }

                PrintDetails2(id,false);


               string ct1 = sqlite.getValue("select count(*) as ct from order_out_detail where order_id='" + id + "' and status='2'", "ct");
               if (ct1.Equals("0"))
               {
                   sqlite.execute("update order_out set status='3' where id='" + id + "'");
               }



            }
        }


        

        private void PrintDetails(string orderid,bool ignore)
        {
            string sql = "select DISTINCT food_id  from 'order_detail_view' where order_id='" + orderid + "' and lang='" + lang + "'";
            if (!ignore)
            {
                sql = "select DISTINCT food_id  from 'order_detail_view' where order_id='" + orderid + "' and lang='" + lang + "' and detail_status='2' ";
            }
            DataTable dt1 = sqlite.getData(sql);

            string report_wenjianming = "Report2.rdlc";

            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                string food_type = dt1.Rows[i]["food_id"].ToString();

                
                DataTable dt2= sqlite.getData("select * from 'printer_binding_view' where food_type='"
                  + food_type + "' and lang='" + lang + "' ");

                if (dt2.Rows.Count == 0)
                {
                    return;
                }

                string printerName= dt2.Rows[0]["printer_name"].ToString();
                string printCount1 = dt2.Rows[0]["print_count"].ToString();
                string paper_width1 = dt2.Rows[0]["paper_width"].ToString();
                string paper_height1 = dt2.Rows[0]["paper_height"].ToString();


                DataTable order_detail = sqlite.getData("select * from 'order_detail_view' where order_id='"
                                        + orderid + "' and food_id = '" + food_type + "'  and lang='" + lang + "' ");

                List<Orders> orders = new List<Orders>();

                string table_name = "";
                string description = "";
                string order_number = "";
                string time = "";
                for (int j = 0; j < order_detail.Rows.Count; j++)
                {
                    

                    List<Orders> orders2_1 = new List<Orders>();

                    string detail_id = order_detail.Rows[j]["id"].ToString();

                    string food_name_ug = order_detail.Rows[j]["food_name"].ToString();
                    string food_price = order_detail.Rows[j]["price"].ToString();

                    table_name = order_detail.Rows[j]["table_name"].ToString();
                    description = order_detail.Rows[j]["description"].ToString();
                    order_number = order_detail.Rows[j]["order_number"].ToString();
                    time = order_detail.Rows[j]["created_at"].ToString();

                    string food_number = order_detail.Rows[j]["number"].ToString();

                    int ct = 0;
                    int.TryParse(food_number, out ct);

                    Orders orders1 = new Orders(food_name_ug, food_price, ct, table_name);

                    orders2_1.Add(orders1);




                    List<ReportParameter> pr1_1 = new List<ReportParameter>();

                    pr1_1.Add(new ReportParameter("order_number", order_number, true));
                    pr1_1.Add(new ReportParameter("table_name", table_name, true));
                    pr1_1.Add(new ReportParameter("description", description, true));
                    pr1_1.Add(new ReportParameter("time", time, true));


                    string path1 = Environment.CurrentDirectory;

                    LocalReport localReport1 = new LocalReport();

                    localReport1.ReportPath = path1 + @"\Report\" + report_wenjianming;

                   

                    int width1 = 0;
                    int.TryParse(paper_width1, out width1);
                    if (width1 <= 0)
                    {
                        return;
                    }

                    int height1 = 0;
                    int.TryParse(paper_height1, out height1);
                    if (height1 <= 0)
                    {
                        return;
                    }

                    //  for (int index = 0; index < cct; index++)
                    //  {
                    RDLCPrint aa1 = new RDLCPrint(true,false);
                    aa1.isDetail1 = true;
                    aa1.Run(localReport1, "DataSet1", orders2_1, pr1_1, printerName, detail_id, printCount1, width1, height1);  //每个饭菜都需要打印一次


                    orders.Add(orders1);
                }


            }
        
                 
            
        }



      

       
        private void PrintDetails2(string orderid, bool ignore)
        {
            string sql = "select DISTINCT food_id  from 'order_out_detail_view' where order_id='" + orderid + "' and lang='" + lang + "'";
            if (!ignore)
            {
                sql = "select DISTINCT food_id  from 'order_out_detail_view' where order_id='" + orderid + "' and lang='" + lang + "' and status='2'";
            }

            DataTable dt1 = sqlite.getData(sql);

            string report_wenjianming = "Report4.rdlc";



            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                string food_type = dt1.Rows[i]["food_id"].ToString();
                

                DataTable dt2 = sqlite.getData("select * from 'printer_binding_view' where food_type='"
                  + food_type + "' and lang='" + lang + "' ");

                if (dt2.Rows.Count == 0)
                {
                    return;
                }

                string printerName = dt2.Rows[0]["printer_name"].ToString();
                string printCount1 = dt2.Rows[0]["print_count"].ToString();
                string paper_width1 = dt2.Rows[0]["paper_width"].ToString();
                string paper_height1 = dt2.Rows[0]["paper_height"].ToString();


                DataTable order_detail = sqlite.getData("select * from 'order_out_detail_view' where order_id='"
                                        + orderid + "' and food_id = '" + food_type + "'  and lang='" + lang + "' ");
                 

               
                string table_name = "";
                string description = "";
                string order_number = "";
                for (int j = 0; j < order_detail.Rows.Count; j++)
                {

                    List<Orders> orders = new List<Orders>();


                    string detail_id = order_detail.Rows[j]["id"].ToString();

                    string food_name_ug = order_detail.Rows[j]["food_name"].ToString();
                    string food_price = order_detail.Rows[j]["price"].ToString();

                    description = order_detail.Rows[j]["description"].ToString();
                    order_number = order_detail.Rows[j]["order_number"].ToString();

                    string food_number = order_detail.Rows[j]["number"].ToString();

                    int ct = 0;
                    int.TryParse(food_number, out ct);

                    Orders orders1 = new Orders(food_name_ug, food_price, ct, table_name);

                    orders.Add(orders1);

                    

                    List<ReportParameter> pr1 = new List<ReportParameter>();

                    string time = sqlite.getValue("select delivery_time from 'order_out' where id='" + orderid + "' and lang='" + lang + "' ", "delivery_time");

                    pr1.Add(new ReportParameter("order_number", order_number, true));
                    pr1.Add(new ReportParameter("time", time, true));
                    pr1.Add(new ReportParameter("description", description, true));

                    
                    string path = Environment.CurrentDirectory;

                    LocalReport localReport = new LocalReport();

                    localReport.ReportPath = path + @"\Report\" + report_wenjianming;

                    string printCount = dt2.Rows[i]["print_count"].ToString();
                    string paper_width = dt2.Rows[i]["paper_width"].ToString();
                    string paper_height = dt2.Rows[i]["paper_height"].ToString();

                    int width = 0;
                    int.TryParse(paper_width, out width);
                    if (width <= 0)
                    {
                        return;
                    }

                    int height = 0;
                    int.TryParse(paper_height, out height);
                    if (height <= 0)
                    {
                        return;
                    }
                    
                    RDLCPrint aa = new RDLCPrint(false,false);

                    aa.isDetail2 = false;

                    aa.Run2(localReport, "DataSet1", orders, pr1, printerName, orderid, printCount, width, height);


                }
            }
        }




        Service service = new Service();
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            string name = btn.Name;
            switch (name)
            {
                case "btn_snc":
                    UpdateUIThreadTest3();
                    break;
                case "btn_refresh":
                    loadGrid1(null);
                    break;
                case "btn_search":
                    break;
                case "food_btn_food_type":

                    StaticDataEditWindow staticDataEditWindow = new StaticDataEditWindow();
                    staticDataEditWindow.Owner = this;
                    staticDataEditWindow.init("food_type", lang);
                    staticDataEditWindow.ShowDialog();

                    break;
                case "food_btn_food_edit":
                    break;
                case "food_btn_search":

                    string tx = food_txt_search.Text;
                    if (string.IsNullOrEmpty(tx))
                    {
                        return;
                    }

                    loadGrid1(" name like '%" + tx + "%'");

                    break;
                case "btn_today":

                    string st_date=DateTime.Now.ToString("yyyy-MM-dd");
                    string ed_date= DateTime.Now.ToString("yyyy-MM-dd");

                    money_start_date.Text = st_date;
                    money_end_date.Text = ed_date;

                    //string start_date = money_start_date.Text;
                    //string end_date = money_end_date.Text;
                    getMoneyData(st_date, ed_date);

                    break;
                case "btn_week":
                    
                    DateTime dt = DateTime.Now;
                   

                    //星期一为第一天  
                     int weeknow = Convert.ToInt32(dt.DayOfWeek);
                    
                    //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
                     weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
                                 int daydiff = (-1) * weeknow;
                    
                    //本周第一天  
                    string FirstDay = dt.AddDays(daydiff).ToString("yyyy-MM-dd");


                    st_date = FirstDay;
                    ed_date = DateTime.Now.ToString("yyyy-MM-dd");
                    money_start_date.Text = st_date;
                    money_end_date.Text = ed_date;

                    getMoneyData(st_date, ed_date);

                    break;
                case "btn_month":

                     dt = DateTime.Now;
                     weeknow = Convert.ToInt32(DateTime.Now.DayOfWeek);
                   int  dayspan = (-1) * weeknow + 1;
                    DateTime dt2 = dt.AddMonths(1);

                    st_date = dt.AddDays(-(dt.Day) + 1).ToString("yyyy-MM-dd");
                    money_start_date.Text = st_date;
                    ed_date = DateTime.Now.ToString("yyyy-MM-dd");
                    //money_start_date.Text = st_date;
                    money_end_date.Text = ed_date;
                    getMoneyData(st_date, ed_date);

                    break;
                case "btn_money_search":
                    //dgv5
                    //money_start_date
                    //money_end_date
                    string start_date= money_start_date.Text;
                    string end_date = money_end_date.Text;
                    getMoneyData(start_date, end_date);


                    break;
            }
        }


        private void getMoneyData(string start_date,string end_date)
        {
            if (string.IsNullOrEmpty(start_date) || string.IsNullOrEmpty(end_date))
            {
                MessageBox.Show("ۋاقتى قۇرۇق بولسا بولمايدۇ");
                return;
            }
            Dictionary<string, string> dict = new Dictionary<string, string>();

            DataTable data = new DataTable();
            data.Columns.Add("name_ug");
            data.Columns.Add("paid_price");
            data.Columns.Add("paid_count");
            data.Columns.Add("canceled_price");
            data.Columns.Add("canceled_count");

            txt_finance_result_label1_1.Text = "0" + "￥";
            txt_finance_result_label2_1.Text = "0";
            txt_finance_result_label3_1.Text = "0" + "￥";
            txt_finance_result_label4_1.Text = "0";

            dgv5.ItemsSource = data.DefaultView;

            start_date = Convert.ToDateTime(start_date).ToString("yyyy-MM-dd");
            end_date = Convert.ToDateTime(end_date).ToString("yyyy-MM-dd");


            string rs = service.getMoneyData(dict, data, start_date, end_date);

            if (!rs.Equals("0"))
            {
                txt_finance_result_label1_1.Text = dict["total_paid_price"] + "￥";
                txt_finance_result_label2_1.Text = dict["total_paid_count"];
                txt_finance_result_label3_1.Text = dict["total_canceled_price"] + "￥";
                txt_finance_result_label4_1.Text = dict["total_canceled_count"];

                dgv5.ItemsSource = data.DefaultView;



            }
            else
            {
                MessageBox.Show("ئۇچۇر تېپىلمىدى");
            }




        }

        private void tab1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void menuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = (MenuItem)sender;
            string name=item.Name;
            switch (name)
            {
                case "menu1_item1":
                    lang = sqlite.getValue("select * from sys_config where name='lang' ", "value");
                           
                    WindowInit windowInit = new WindowInit();
                    windowInit.Owner = this;
                    windowInit.lang = lang;
                    windowInit.Show();
                    // this.Close();
                    break;
            }
        }

        private void Menu1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (menu1.SelectedIndex == 0)
            {
                lang = sqlite.getValue("select * from sys_config where name='lang' ", "value");

                WindowInit windowInit = new WindowInit();
                windowInit.lang = lang;
                windowInit.Show();
                this.Close();
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            string nm = btn.Name;
            switch (nm)
            {
                case "btn_order_type1":
                    btn_order_type1.IsEnabled = false;
                    btn_order_type2.IsEnabled = true;

                    dgv3.Visibility = Visibility.Visible;
                    dgv4.Visibility = Visibility.Hidden;
                    break;
                case "btn_order_type2":
                    btn_order_type1.IsEnabled = true;
                    btn_order_type2.IsEnabled = false;
                    dgv3.Visibility = Visibility.Hidden;
                    dgv4.Visibility = Visibility.Visible;
                    break;
            }
            loadGrid3();

        }

        private void Food_edit_combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {


        }
    }
}
